<template>
  <button class="xtx-button ellipsis" :class="[size, type]" @click="addcart" >
    <slot />
  </button>

</template>
<script>
import { cartadd } from "@/utils/Api/NavText";
export default {
  name: "XtxButton",
  props: {
    size: {
      type: String,
      default: "middle",
    },
    type: {
      type: String,
      default: "default",
    },
    skuobj: {
      type: Object,
    },
    number: {
      type: Number,
    },
    infoobj: {
      type: Object,
    },
  },
  // /添加商品到购物车
  methods: {
    async addcart() {
      if (
        this.$store.state.user.userinfo &&
        this.$store.state.user.userinfo.token
      ) {
        let res = await cartadd(this.skuobj.skuid, this.number);
        if (res.msg == "操作成功") {
          this.$store.dispatch("cart/asynccartlist");
        }
      } else {
        //查看规格是否合适
        if (!this.skuobj.skuid) {
          this.$msg({ text: "请选择合适规格再加入", type: "error" });
          return false;
        }
        //判断库存是否充足 number
        if (this.skuobj.inventory < this.number) {
          this.$msg({ text: "库存不足", type: "error" });
          return false;
        }
        //判断当前规格的产品是否在规格存在
        var index = this.$store.state.cart.list.findIndex(
          (item) => item.skuid == this.skuobj.skuid
        );
        if (index == -1) {
          //存商品
          var obj = {
            ...this.skuobj,
            count: this.number,
            selected: true,
            name: this.infoobj.name,
            picture: this.infoobj.mainPictures[0],
            price: this.skuobj.price,
            skuId: this.skuobj.skuId,
            attrsText: this.skuobj.skuname,
            isCollect: false,
            nowPrice: this.skuobj.price,
          };
          this.$store.commit("cart/addlist", obj);
        } else {
          //改数量
          this.$store.commit("cart/changenum", { index, number: this.number });
        }
      }
    },
  },
};
</script>
<style scoped lang="scss">
@import "@/assets/css/color.scss";
.xtx-button {
  appearance: none;
  border: none;
  outline: none;
  background: #fff;
  text-align: center;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
}
.large {
  width: 240px;
  height: 50px;
  font-size: 16px;
}
.middle {
  width: 180px;
  height: 50px;
  font-size: 16px;
}
.small {
  width: 100px;
  height: 32px;
  font-size: 14px;
}
.mini {
  width: 60px;
  height: 32px;
  font-size: 14px;
}
.default {
  border-color: #e4e4e4;
  color: #666;
}
.primary {
  border-color: $xtxColor;
  background: $xtxColor;
  color: #fff;
}
.plain {
  border-color: $xtxColor;
  color: $xtxColor;
  background: lighten($xtxColor, 50%);
}
.gray {
  border-color: #ccc;
  background: #ccc;
  color: #fff;
}
</style>
